<?php

class User_Model_Table_Role_Config extends Database_Table
{
	protected $_name = 'user_role_configs';

	public function get($role_id, $nameset, $default = null)
	{
		$select = $this -> select() -> where('resource_id=?', intval($role_id)) -> where('nameset=?', (string)$nameset);

		$rows = $this -> fetchAll($select);

		if ($rows -> count())
		{
			$result = array();
			foreach ($rows as $row)
			{
				$result[$row -> getName()] = $row -> getData();
			}
			return $result;
		}
		return $default;
	}

	public function set($role_id, $nameset, $data)
	{
		// check that group is exists.

		if (is_string($data) or !is_array($data))
		{
			throw new Agilet_Exception('configure set require data is an array.');
		}

		foreach ($data as $name => $value)
		{
			$row = $this -> fetchRow($this -> select() > where('resource_id=?', intval($role_id)) -> where('nameset=?', (string)$nameset) -> where('name=?', $name));

			if (is_object($row) == false)
			{
				$row = $this -> fetchNew();
				$row -> role_id = (string)$role_id;
				$row -> nameset = (string)$nameset;
				$row -> name = (string)$name;
			}
			$row -> data = $value;
			$row -> save();
		}
		return true;
	}

}
